<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    .comment-textarea {
      border: 1px solid rebeccapurple;
      width: 100%;
      height: 300px;
    }

    .ss {
      height: 40px;
    }
  </style>
</head>

<body>
  <div>在线测试bbbsss</div>
  <span id="test"></span>
  <textarea id="comment-box" class="comment-textarea" maxlength="500" placeholder="来都来了就说点什么吧~"
    oninput="func()"></textarea>
  <div class="ss">安舒服了说说发撒的发是是的s</div>
  <div class="ss">安舒服了说说发撒的发是是的s</div>
  <div class="ss">安舒服了说说发撒的发是是的s</div>
  <div class="ss">安舒服了说说发撒的发是是的s</div>
  <div class="ss">安舒服了说说发撒的发是是的s</div>
  <script>
    //输入框获取光标
    const getPosition = function (element) {
      let cursorPos = 0;
      if (document.selection) {//IE
        var selectRange = document.selection.createRange();
        selectRange.moveStart('character', -element.value.length);
        cursorPos = selectRange.text.length;
      } else if (element.selectionStart || element.selectionStart == '0') {
        cursorPos = element.selectionStart;
      }
      return cursorPos;
    }

    function func() {
      var elm = document.getElementById('comment-box');
      var x = elm.value;
      document.getElementById('test').innerText = x;
      const num = getPosition(elm);
      if (x.charAt(num - 1) === '@') {
        console.log('输入了@')
      }


    }
    // var elm = document.getElementById('comment-box');
    // elm.addEventListener('onkeyup', function (e) {
    //   document.getElementById('test').innerText = e.key
    // })
  </script>
</body>

</html>